﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.UserCommand;
using MD5Hash;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.UserHandler
{
    public class CreateUserHandler : IRequestHandler<CreateUserCommand, APIResult<object>>
    {
        private readonly IBaseRepository<User> userRepo;
        private readonly IMapper mapper;
        private readonly ILogger<CreateUserHandler> logger;

        public CreateUserHandler(IBaseRepository<User> userRepo, IMapper mapper, ILogger<CreateUserHandler> logger)
        {
            this.userRepo = userRepo;
            this.mapper = mapper;
            this.logger = logger;
        }

        public Task<APIResult<object>> Handle(CreateUserCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                var model = mapper.Map<User>(request);
                model.Pass = request.Pass.GetMD5();
                model.IsDeleted = false;
                model.CreateTime = DateTime.Now;
                var s=userRepo.AddAsync(model).Result;
                if (s > 0)
                {
                    result.Code = APIEnum.Success;
                    result.Msg = "添加成功";
                    result.Data = s;
                    logger.LogInformation($"用户{model.Name}添加成功");
                }
                else
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "添加失败";
                    result.Data = s;
                    logger.LogError($"用户{model.Name}添加失败");
                }
                return Task.FromResult(result);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
